package com.park.platform.service.impl;

import com.park.common.constant.IDBConstant;
import com.park.common.constant.IPlatformConstant;
import com.park.common.exception.MessageException;
import com.park.common.poo.*;
import com.park.common.util.Arith;
import com.park.common.util.DateUtil;
import com.park.common.util.StrUtil;
import com.park.platform.dao.IBaseDao;
import com.park.platform.service.IOperatorService;
import com.park.wx.pojo.SNSUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OperatorServiceImpl extends BaseService implements IOperatorService {

	@Autowired
	private IBaseDao baseDao;

	@Override
	public UserOperator getUserOperator(int id) {
		return baseDao.getToEvict(UserOperator.class, id);
	}

	@Override
	public Integer getNowDatePoint(int id){
		Number point = baseDao.getUniqueResult("SELECT SUM(point) FROM system_merit_info WHERE createDate = ? AND id = ?", DateUtil.dateToString(new Date(), DateUtil.YYYYMMDD), id);
		return point != null ? point.intValue() : 0;
	}

	@Override
	public UserOperator getOperator(String openId){
		return baseDao.queryByHqlFirst("FROM UserOperator WHERE openId = ?", openId);
	}

	@Override
	public UserOperator login(String mobile, String pwd){
		if(!StrUtil.isMobile(mobile)) throw new MessageException("请输入正确的手机号");
		if(StrUtil.isBlank(pwd)) throw new MessageException("请输入密码");
		UserOperator userOperator = baseDao.queryByHqlFirst("SELECT u FROM UserOperator u, SystemRoleOperator s WHERE u.id = s.id.id AND s.id.roleId = ? AND u.operatorMobile = ?", IDBConstant.ROLE_COMMON, mobile);
		if(userOperator == null) throw new MessageException("手机号不存在");
		if(!userOperator.getOperatorPwd().equals(pwd)) throw new MessageException("密码错误");
		return userOperator;
	}

	@Override
	public void addUserOperator(UserOperator userOperator){
		check(userOperator);
		if(StrUtil.isBlank(userOperator.getOperatorPwd())) throw new MessageException("请输入密码");
		userOperator.setCreateTime(DateUtil.getNowDate());
		userOperator.setNo(this.getNo());
		baseDao.save(userOperator, null);

		SystemRoleOperator systemRoleOperator = new SystemRoleOperator(new SystemRoleOperatorId(IDBConstant.ROLE_COMMON, userOperator.getId()));
		baseDao.save(systemRoleOperator, null);
	}

	@Override
	public void addAdminUserOperator(UserOperator userOperator){
		Integer id = userOperator.getId();
		if(id == null) {
			if (StrUtil.isBlank(userOperator.getOperatorMobile())) throw new MessageException("请输入员工登录账号");
			if (getUserOperatorByMobile(userOperator.getOperatorMobile()) != null) throw new MessageException("员工登录账号已存在");
			if (StrUtil.isBlank(userOperator.getOperatorName())) throw new MessageException("请输入员工姓名");
			if (StrUtil.isBlank(userOperator.getOperatorPwd())) throw new MessageException("请输入密码");
			userOperator.setOperatorType(IDBConstant.OPERATOR_TYPE_ADMIN);
			userOperator.setNo(getNo());
			userOperator.setCreateTime(DateUtil.getNowDate());
			baseDao.save(userOperator, null);

			SystemRoleOperator systemRoleOperator = new SystemRoleOperator(new SystemRoleOperatorId(IDBConstant.ROLE_ADMIN, userOperator.getId()));
			baseDao.save(systemRoleOperator, null);
		}else{
			UserOperator userOperatorDB = getUserOperator(id);
			userOperatorDB.setOperatorName(userOperator.getOperatorName());
			userOperatorDB.setOperatorMobile(userOperator.getOperatorMobile());
			userOperatorDB.setOperatorPwd(userOperator.getOperatorPwd());
			baseDao.save(userOperatorDB, id);
		}
	}

	@Override
	public void deleteAdminUserOperator(int id){
		UserOperator userOperator = getUserOperator(id);
		if(userOperator != null && IDBConstant.OPERATOR_TYPE_ADMIN.equals(userOperator.getOperatorType())) {
			baseDao.delete(userOperator);
			baseDao.delete("system_role_operator", "id", id);
		}
	}

	private String getNo(){
		Integer no = 0;
		do {
			no = 10000 + new Random().nextInt(89999);
		}while (baseDao.queryBySqlFirst("SELECT 1 FROM user_operator WHERE no = ?", StrUtil.objToStr(no)) != null);
		return StrUtil.objToStr(no);
	}

	@Override
	public void registerCaptcha(UserOperator userOperator){
		check(userOperator);
	}

	private void check(UserOperator userOperator) {
		if(StrUtil.isBlank(userOperator.getOperatorName())) throw new MessageException("请输入昵称");
		if(!StrUtil.isMobile(userOperator.getOperatorMobile())) throw new MessageException("请输入正确的手机号");
		if(getUserOperatorByName(userOperator.getOperatorName()) != null) throw new MessageException("昵称已存在，换一个吧");
		if(getUserOperatorByMobile(userOperator.getOperatorMobile()) != null) throw new MessageException("手机已存在，换一个吧");
	}

	@Override
	public UserOperator getUserOperatorByMobile(String mobile){
		return baseDao.queryByHqlFirst("FROM UserOperator WHERE operatorMobile = ?", mobile);
	}

	@Override
	public UserOperator getUserOperatorByName(String name){
		return baseDao.queryByHqlFirst("FROM UserOperator WHERE operatorName = ?", name);
	}

	@Override
	public void updateUserSign(UserSign userSign) throws Exception{
		UserOperator userOperator = getUserOperator(userSign.getId());
		String signDate = DateUtil.dateToString(new Date(), DateUtil.YYYYMMDD);

		if(signDate.equals(userOperator.getLastSignDate())) throw new MessageException("今日已签到，明日再来吧:)");

		String nowDate = DateUtil.getNowDate();

		userSign.setSignDate(signDate);
		userSign.setCreateTime(nowDate);
		baseDao.save(userSign, null);

		userOperator.setMeritPoint(userOperator.getMeritPoint() + IPlatformConstant.POINT);
		userOperator.setLastSignDate(signDate);
		baseDao.save(userOperator, userOperator.getId());

		SystemMeritInfo systemMeritInfo = new SystemMeritInfo();
		systemMeritInfo.setCreateTime(nowDate);
		systemMeritInfo.setPoint(IPlatformConstant.POINT);
		systemMeritInfo.setId(userOperator.getId());
		systemMeritInfo.setCreateDate(signDate);
		systemMeritInfo.setServiceType(IDBConstant.LOGIC_STATUS_YES);
		baseDao.save(systemMeritInfo, null);
	}

	@Override
	public void newCollector(UserCollector userCollector){
		UserCollector collector = getUserCollector(userCollector.getServiceType(), userCollector.getServiceId(), userCollector.getId());
		if(collector != null){
			baseDao.delete(collector);
		}else{
			userCollector.setCreateTime(DateUtil.getNowDate());
			baseDao.save(userCollector, null);
		}
	}

	@Override
	public UserCollector getUserCollector(String serviceType, int serviceId, int uid){
		return baseDao.queryByHqlFirst("FROM UserCollector WHERE serviceType = ? AND serviceId = ? AND id = ?", serviceType, serviceId, uid);
	}

	@Override
	public UserOperator getUserOperator(String no){
		return baseDao.queryByHqlFirst("FROM UserOperator WHERE no = ?", no);
	}

	@Override
	public UserOperator getUserOperatorByFenxiao(String no){
		return baseDao.queryByHqlFirst("SELECT new UserOperator(id, operatorName, no, operatorMobile, superior) FROM UserOperator WHERE no = ?", no);
	}

	@Override
	public List<UserOperator> getUserOperatorBySubordinate(String no){
		return baseDao.queryByHql("SELECT new UserOperator(id, operatorName, no, operatorMobile, superior) FROM UserOperator WHERE superior LIKE ?", "%;" + no + ";%");
	}

	@Override
	public List<UserOperator> getUserOperatorListByFenxiao(){
		List<UserOperator> subordinateList = baseDao.queryByHql("SELECT new UserOperator(u.id, u.operatorName, u.no, u.operatorMobile, u.superior) FROM UserOperator u, SystemRoleOperator s WHERE u.id = s.id.id AND s.id.roleId = ?", IDBConstant.ROLE_COMMON);

		return subordinateList;
	}

	/*******************************************************************************************************************/

	@Override
	public UserOperator loginIn(String mobile, String pwd){
		UserOperator userOperator = baseDao.queryByHqlFirst("SELECT u FROM UserOperator u, SystemRoleOperator s WHERE u.id = s.id.id AND s.id.roleId = ? AND u.operatorMobile = ?", IDBConstant.ROLE_ADMIN, mobile);
		if(userOperator == null) throw new MessageException("账号不存在");
		if(!userOperator.getOperatorPwd().equals(pwd)) throw new MessageException("密码错误");
		return userOperator;
	}

	@Override
	public void updatePassword(String oldPwd, String newPwd, int uid){
		UserOperator userOperator = getUserOperator(uid);
		if(!userOperator.getOperatorPwd().equals(oldPwd)) throw new MessageException("原始密码错误");
		userOperator.setOperatorPwd(newPwd);
		baseDao.save(userOperator, userOperator.getId());
	}

	@Override
	public List<UserOperator> getSuperior(int uid){
		List<UserOperator> userOperatorList = new ArrayList<>();
		UserOperator userOperator = getUserOperator(uid);
		if(userOperator == null) throw new MessageException("账号不存在");
		String superior = userOperator.getSuperior();
		if(StrUtil.isNotBlank(superior)){
			List<String> userNos = Arrays.asList(superior.split(";"));
			Collections.reverse(userNos);
			for (String no : userNos){
				if(StrUtil.isNotBlank(no)) {
					UserOperator superiorUser = getUserOperatorByFenxiao(no);
					if(superiorUser != null){
						userOperatorList.add(superiorUser);
					}
				}
			}
		}
		return userOperatorList;
	}

	@Override
	public Map<String, List<UserOperator>> getSubordinate(int uid){

		Map<String, List<UserOperator>> userSubordinates = new LinkedHashMap<>();
		List<UserOperator> firstLevel = new ArrayList<>();
		List<UserOperator> secondLevel = new ArrayList<>();
		List<UserOperator> thirdLevel = new ArrayList<>();

		UserOperator userOperator = getUserOperator(uid);
		String currUserNo = userOperator.getNo();

		List<UserOperator> subordinateList = getUserOperatorBySubordinate(currUserNo);
		if(subordinateList != null && subordinateList.size() > 0){
			for(UserOperator subordinate : subordinateList){
				String levelNos = subordinate.getSuperior();
				if (StrUtil.isNotBlank(levelNos)) {
					String[] leverNoArr = levelNos.split(";");
					int i = leverNoArr.length - 1;
					for (int j = 1; i > 0; j++) {
						if (StrUtil.isNotBlank(leverNoArr[i])) {
							UserOperator levelUser = getUserOperatorByFenxiao(leverNoArr[i]);
							if (levelUser != null) {
								if ((j == 1) && (StrUtil.equals(currUserNo, leverNoArr[i])))
									firstLevel.add(subordinate);
								else if ((j == 2) && (StrUtil.equals(currUserNo, leverNoArr[i])))
									secondLevel.add(subordinate);
								else if ((j == 3) && (StrUtil.equals(currUserNo, leverNoArr[i])))
									thirdLevel.add(subordinate);
							}
						}
						i--;
					}
				}
			}
		}

		userSubordinates.put("firstLevel", firstLevel);
		userSubordinates.put("secondLevel", secondLevel);
		userSubordinates.put("thirdLevel", thirdLevel);
		return userSubordinates;
	}

	@Override
	public void updateUserFenxiao(int uid, int subUid){
		UserOperator recomUser = getUserOperator(uid);
		if(recomUser != null){
			String superior = recomUser.getSuperior();
			UserOperator subordinateUser = getUserOperator(subUid);
			if(subordinateUser != null){
				String recomNo = recomUser.getNo();
				int index = 0;
				if(StrUtil.isNotBlank(superior) && (index=superior.indexOf(subordinateUser.getNo())) > 0) throw new MessageException("【"+subordinateUser.getOperatorName()+"】是该用户的"+(superior.split(";").length-index)+"级上级用户，不能添加此用户为下级用户!");
				if (StrUtil.isBlank(superior)) {
					subordinateUser.setSuperior(";" + recomNo + ";");
				} else if (superior.split(";").length > 3)
					subordinateUser.setSuperior(";" + superior.split(";", 3)[2] + recomNo + ";");
				else {
					subordinateUser.setSuperior(superior + recomNo + ";");
				}
				baseDao.save(subordinateUser, subordinateUser.getId());
			}
		}
	}

	@Override
	public void deleteUserFenxiao(int uid, int subUid){
		UserOperator recomUser = getUserOperator(uid);
		if(recomUser != null){
			UserOperator subordinateUser = getUserOperator(subUid);
			if(subordinateUser != null){
				String superior = subordinateUser.getSuperior();
				if(StrUtil.isNotBlank(superior)){
					String[] nos = superior.split(";");
					if(nos.length == 2) subordinateUser.setSuperior(null);
					else subordinateUser.setSuperior(superior.replace(";"+recomUser.getNo(), StrUtil.EMPTY));
					baseDao.save(subordinateUser, subordinateUser.getId());
				}
			}
		}
	}

	@Override
	public void newCommission(int uid, double commission){
		UserOperator userOperator = getUserOperator(uid);
		userOperator.setCommission(Arith.getBigDecimal(commission >= 0 ? commission : 0));
		baseDao.save(userOperator, userOperator.getId());
	}

	/*******************************************************************************************************************/
	@Override
	public UserOperator saveShareOperator(String shareOpenId, SNSUserInfo snsUserInfo){

		String openId = snsUserInfo.getOpenId();

		String nowDate = DateUtil.getNowDate();
		UserOperator operatorDB = getOperator(openId);
		if(operatorDB != null) { //不是新用户，只是点击了分享链接的老用户，（顺便更新用户昵称和头像信息）
			operatorDB.setOperatorName(snsUserInfo.getNickname());
			operatorDB.setHeadImg(snsUserInfo.getHeadImgUrl());
			operatorDB.setUpdateTime(nowDate);
			baseDao.save(operatorDB, operatorDB.getId());
			return operatorDB;
		}
		//if(shareOpenId != null && getOperator(shareOpenId) == null) return null; //分享的用户openId（分享人不存在，有人故意搞破坏）

		//新用户
		UserOperator operator = new UserOperator();
		operator.setOpenId(openId);
		operator.setOperatorName(snsUserInfo.getNickname());
		operator.setHeadImg(snsUserInfo.getHeadImgUrl());
		operator.setStatus(IDBConstant.LOGIC_STATUS_YES);
		operator.setCreateTime(nowDate);
		operator.setNo(this.getNo());
		baseDao.save(operator, null);

		SystemRoleOperator operatorRole = new SystemRoleOperator();
		System.out.println("========"+operator.getId()+"==============");
		SystemRoleOperatorId pk = new SystemRoleOperatorId();
		pk.setId(operator.getId());
		pk.setRoleId(IDBConstant.ROLE_COMMON);
		operatorRole.setId(pk);
		baseDao.save(operatorRole, null);

		//加经验，雷达币
		//pointRulerService.addPoints(openId, null, IDBConstant.POINT_SERVICE_INTEREST, IDBConstant.POINT_TYPE_EXPERIENCE, IDBConstant.POINT_TYPE_COIN);

		return operator;
	}

	@Override
	public void newAddOperatorPoint(){
		List<UserOperator> userOperatorList = baseDao.queryByHql("SELECT o FROM UserOperator o, SystemRoleOperator so WHERE o.id = so.id.id AND so.id.roleId = ?", IDBConstant.ROLE_COMMON);

		String signDate = DateUtil.dateToString(new Date(), DateUtil.YYYYMMDD);
		String nowDate = DateUtil.getNowDate();
		for(UserOperator userOperator : userOperatorList){
			userOperator.setMeritPoint(userOperator.getMeritPoint() + IPlatformConstant.POINT);
			baseDao.save(userOperator, userOperator.getId());

			SystemMeritInfo systemMeritInfo = new SystemMeritInfo();
			systemMeritInfo.setCreateTime(nowDate);
			systemMeritInfo.setPoint(IPlatformConstant.POINT);
			systemMeritInfo.setId(userOperator.getId());
			systemMeritInfo.setCreateDate(signDate);
			systemMeritInfo.setServiceType(IDBConstant.LOGIC_STATUS_YES);
			baseDao.save(systemMeritInfo, null);
		}

	}

	
}
